import os
import time
import pandas as pd
import matplotlib.pyplot as plt


import PySide2
from PySide2.QtWidgets import QApplication, QMessageBox, QFileDialog
from PySide2.QtUiTools import QUiLoader


# 图片设定中文
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = ['Microsoft Yahei']


# 环境问题，重要！！
dirname = os.path.dirname(PySide2.__file__)
plugin_path = os.path.join(dirname, 'plugins', 'platforms')
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = plugin_path


class VisualExe:

    def __init__(self):
        # 从UI定义中动态 创建一个相应的窗口对象
        # 注意：里面的控件对象也成为窗口对象的属性了
        # 比如self.ui.button, self.ui.textEdit
        loader = QUiLoader()
        self.ui = loader.load(r'./ui/visual-plt.ui')
        self.ui.line_button.clicked.connect(self.handle_line)
        self.ui.pie_button.clicked.connect(self.handle_pie)
        self.ui.bar_button.clicked.connect(self.handle_bar)
        self.error = None
        self.pwd = os.getcwd()

    def log(self, msg):
        now = time.strftime("%Y-%m-%d %H:%M:%S")
        event = now + ": " + msg
        self.ui.log.append(event)

    def handle_line(self):
        file_path, _ = QFileDialog.getOpenFileName(self.ui, "选择你要上传的文件", self.pwd, "Excel文件 (*.xls *.xlsx)")
        if file_path:
            try:
                self.error = "获取文件名称"
                file_name = file_path[file_path.rindex("/") + 1: file_path.rindex(".")]
                file_output_path = self.pwd + "\\" + file_name

                self.log("读取Excel文件")
                self.error = "Excel文件读取"
                df = pd.read_excel(file_path)
                self.log("读取成功")

                self.log("检查输入数据")
                self.error = "数据格式"
                self.log("检查通过")

                self.log("按日期排序")
                df.sort_values(by=df.columns[0], inplace=True)  # 按日期排序
                self.log("排序成功")
                x = [i.date() for i in df.iloc[:, 0].to_list()]
                x_label = df.columns[0]
                y = df.iloc[:, 1].to_list()
                y_label = df.columns[1]

                self.log("绘图")
                self.error = "matplotlib绘图"
                fig, ax = plt.subplots()
                ax.plot(x, y)
                ax.set(xlabel=x_label, ylabel=y_label, title=file_name)
                ax.grid(axis="y")
                plt.setp(ax.get_xticklabels(), rotation=45)
                plt.tight_layout()
                fig.savefig(file_output_path)
                self.log("绘图完毕")

                choice = QMessageBox.question(self.ui, '确认', '要打开图片吗？')
                if choice == QMessageBox.Yes:
                    self.log("打开图像")
                    plt.show()
                    self.log("打开成功")
                else:
                    self.log("选择不打开图像")
                plt.close()
            except:
                self.log("出错了，请检查" + self.error)
                # QMessageBox.critical(self.ui, "Error", "出错了，请检查" + self.error)

    def handle_pie(self):
        # Pie chart, where the slices will be ordered and plotted counter-clockwise:
        labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
        sizes = [15, 30, 45, 10]
        explode = (0, 0.1, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')
        fig1, ax1 = plt.subplots()
        ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90)
        ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

        choice = QMessageBox.question(self.ui, '确认', '要打开图片吗？')
        if choice == QMessageBox.Yes:
            plt.show()

    def handle_bar(self):
        labels = ['G1', 'G2', 'G3', 'G4', 'G5']
        men_means = [20, 35, 30, 35, 27]
        women_means = [25, 32, 34, 20, 25]
        men_std = [2, 3, 4, 1, 2]
        women_std = [3, 5, 2, 3, 3]
        width = 0.35  # the width of the bars: can also be len(x) sequence

        fig, ax = plt.subplots()

        ax.bar(labels, men_means, width, yerr=men_std, label='Men')
        ax.bar(labels, women_means, width, yerr=women_std, bottom=men_means,
               label='Women')

        ax.set_ylabel('Scores')
        ax.set_title('Scores by group and gender')
        ax.legend()

        choice = QMessageBox.question(self.ui, '确认', '要打开图片吗？')
        if choice == QMessageBox.Yes:
            plt.show()

app = QApplication([])
stats = VisualExe()
stats.ui.show()
app.exec_()
